const app = getApp()
const { processImageUrl } = require('../../utils/image')
const request = require('../../utils/request.js');
Page({
  data: {
    currentTab: '',
    orderList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  onLoad: function () {
    this.loadOrderList()
  },

  onShow: function () {
    if(app.globalData.needRefresh) {
      this.loadOrderList();
      app.globalData.needRefresh = false;
    }
  },

  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      hasMore: true,
      orderList: []
    })
    this.loadOrderList().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreOrderList()
      this.setData({
        loading: true
      })
    }
  },

  // 加载订单列表
  loadOrderList: function () {
    return new Promise((resolve, reject) => {
      request.request({
        url: `${app.globalData.baseUrl}/api/orders`,
        method: 'GET',
        data: {
          page: this.data.page,
          pageSize: this.data.pageSize,
          status: this.data.currentTab
        },
        header: {
          'Authorization': `Bearer ${app.getGlobalToken()}`
        },
        success: (res) => {
          const {
            list,
            total
          } = res.data.data
          // 使用工具函数处理图片URL
          // const processedList = processListImages(list)
          list.map((item) => {
            item.residue.image = processImageUrl(item.residue.image)
            return item
          })
          this.setData({
            orderList: list,
            hasMore: this.data.orderList.length + list.length < total
          })
          resolve()
        },
        fail: reject
      })
    })
  },

  // 加载更多订单列表
  loadMoreOrderList: function () {
    this.setData({
      page: this.data.page + 1
    })
    this.loadOrderList().then(() => {
      this.setData({
        loading: false
      })
    })
  },

  // 切换标签
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: tab,
      page: 1,
      hasMore: true,
      orderList: []
    })
    this.loadOrderList()
  },

  // 跳转到详情页
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/orders/detail/detail?id=${id}`
    })
  },

  // 取消订单
  cancelOrder: function (e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          request.request({
            url: `${app.globalData.baseUrl}/api/orders/${id}/cancel`,
            method: 'POST',
            header: {
              'Authorization': `Bearer ${app.getGlobalToken()}`
            },
            success: () => {
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              })
              this.refreshOrderList()
            }
          })
        }
      }
    })
  },

  // 支付订单
  payOrder: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/orders/pay/pay?id=${id}`
    })
  },

  // 联系卖家
  contactSeller: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/chat/chat?orderId=${id}`
    })
  },

  // 确认收货
  confirmReceive: function (e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确认已收到货物？',
      success: (res) => {
        if (res.confirm) {
          request.request({
            url: `${app.globalData.baseUrl}/api/orders/${id}/confirm`,
            method: 'POST',
            header: {
              'Authorization': `Bearer ${app.globalData.token}`
            },
            success: () => {
              wx.showToast({
                title: '确认收货成功',
                icon: 'success'
              })
              this.refreshOrderList()
            }
          })
        }
      }
    })
  },

  // 删除订单
  deleteOrder: function (e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要删除该订单吗？',
      success: (res) => {
        if (res.confirm) {
          request.request({
            url: `${app.globalData.baseUrl}/api/orders/${id}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${app.globalData.token}`
            },
            success: () => {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.refreshOrderList()
            }
          })
        }
      }
    })
  },

  // 评价订单
  writeReview: function (e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/orders/review/review?id=${id}`
    })
  },

  // 刷新订单列表
  refreshOrderList: function () {
    this.setData({
      page: 1,
      hasMore: true,
      orderList: []
    })
    this.loadOrderList()
  }
})